package com.pig4cloud.pig.common.feign.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bblocks.enums.SysEnum;
import com.bblocks.exception.ServiceException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//@Configuration
public class FeignErrorDecoder implements ErrorDecoder
{
	@Override
	public Exception decode(String methodKey, Response response)
	{
		try
		{
			// 获取异常信息
			String message = Util.toString(response.body().asReader(Util.UTF_8));
			log.error(message); //记录日志
			JSONObject jsonObject = JSONUtil.parseObj(message) ;

			//直接上抛自定义异常
			// return new BizException(jsonObject.getInteger("code"), jsonObject.getString("msg"));
			return new ServiceException(jsonObject.getInt("code"), jsonObject.getStr("msg"));
		}
		catch (Exception ex)
		{
			//1、调用参数异常
			if (response.status() >= 400 && response.status() <= 500)
			{
				return new ServiceException(SysEnum.SYS_SERVER_INVALID_REQUEST);
			}
			else
			{
				return new ServiceException(SysEnum.SYS_SERVER_INTERNAL_ERROR);
			}
		}
	}
}